<template>
  <micro-app
    v-show="state.status === 'mounted'"
    v-bind="$attrs"
    wh-full
    overflow-auto
    @created="handleCreated"
    @beforemount="handleBeforemount"
    @mounted="handleMounted"
    @unmount="handleUnmount"
    @error="handleError"
  />

  <div v-show="state.status !== 'mounted'" wh-full flex items-center justify-center>
    <n-empty :description="state.status === 'error' ? '渲染出错了' : ''">
      <template #icon>
        <TheIcon v-if="state.status === 'loading'" icon="svg-spinners:bars-scale-middle" :size="40" />
        <CustomIcon v-else icon="tabler-face-id-error" :size="40" />
      </template>

      <template #default>
        <template v-if="state.status === 'error'">
          <span v-if="state.error === 'Failed to fetch'">连接无响应</span>
          <span v-else>加载出错</span>
        </template>
        <span v-else-if="state.status === 'unmounted'">应用已卸载</span>
        <span v-else-if="state.status === 'loading'">加载中...</span>
      </template>
    </n-empty>
  </div>
</template>

<script setup lang="ts">
const state = reactive({
  status: 'loading',
  error: ''
})

function handleCreated() {
  console.log('micro-app元素被创建')
}

function handleBeforemount() {
  console.log('即将被渲染')
}

function handleMounted() {
  console.log('已经渲染完成')
  state.status = 'mounted'
}

function handleUnmount() {
  console.log('已经卸载')
  state.status = 'unmounted'
}

function handleError(e: TRecord<any>) {
  const error = e.detail?.error?.message || ''
  console.log('加载出错', e)
  state.status = 'error'
  state.error = error
}
</script>
